package com.difsonapps.android.joinme;

import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.AbstractMap.SimpleEntry;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Map.Entry;

import com.difsonapps.android.joinme.db.Contact;
import com.difsonapps.android.joinme.db.DataBaseViewMapHistory;
import com.difsonapps.android.joinme.db.DatabaseHandler;
import com.difsonapps.android.joinme.db.ViewMapHistoryTable;

import android.app.Activity;
import android.app.ActionBar;
import android.app.Fragment;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.net.wifi.p2p.WifiP2pManager.ActionListener;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v4.app.TaskStackBuilder;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.os.Build;
import android.provider.ContactsContract;

public class ContactDetailActivity extends Activity {
	private final String TAG = this.getClass().getSimpleName();
	
	PlaceholderFragment fragment;
	String currentContact = null;
	
	DataBaseViewMapHistory db;
	ViewMapHistoryTable vmht;
	long contactid;
	GlobalVariables glbVar;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_contact_detail);
		getActionBar().setDisplayHomeAsUpEnabled(true);
		getActionBar().setDisplayUseLogoEnabled(false);
		fragment = new PlaceholderFragment();
		if (savedInstanceState == null) {
			getFragmentManager().beginTransaction()
					.add(R.id.container, fragment).commit();
		}
	
		Intent intent = this.getIntent();
	   currentContact = intent.getStringExtra("id");
	   contactid = Long.valueOf(currentContact);
		if(db==null)
		{
			 db = new DataBaseViewMapHistory(this);
		}
		
		glbVar = GlobalVariables.getInstance();
			
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {

		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.contact_detail, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		switch (id) {
		case R.id.action_settings:
			return true;
		case android.R.id.home:
			Intent upIntent = NavUtils.getParentActivityIntent(this);
			upIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP); 
			NavUtils.navigateUpTo(this, upIntent);
	        return true;
		default:
			break;
		}
		return super.onOptionsItemSelected(item);
	}

	public void buttonOnClick(View v){
		switch (v.getId()) {
	      case R.id.btn_map:
		     if(currentContact!=null)
		     {

		     	 Calendar c = Calendar.getInstance();
		    	 long id = db.addContactViewMap(new ViewMapHistoryTable(contactid,c.getTime()));
		    	 Log.d(TAG, String.valueOf(id) ); 
		    	 glbVar.getViewMapHistoryFragment().Update(id);
		    	 
		    	  Intent intentmap = new Intent(this, MapActivity.class);
	              Bundle bundlemap = new Bundle();
	              bundlemap.putString ("id", currentContact);
	              intentmap.putExtras(bundlemap);
	              startActivity(intentmap);
		    	 
		     }
             
	        break;
	      case R.id.btn_call:

	        break;
	        
	      case R.id.btn_message:
	    	
	    	     if(currentContact!=null)
	    	     {
	    	    	  Intent intent = new Intent(this, TChatActivity.class);
	                  Bundle bundle = new Bundle();
	                  bundle.putString ("id", currentContact);
	                  intent.putExtras(bundle);
	                  startActivity(intent);
	    	     }
	    	
		        break;
		}
	}
		
	/**
	 * A placeholder fragment containing a simple view.
	 */
	public static class PlaceholderFragment extends Fragment {
		long id;
		DatabaseHandler db;
		View rootView;

		public PlaceholderFragment() {
		
		}

		@Override
		public View onCreateView(LayoutInflater inflater, ViewGroup container,
				Bundle savedInstanceState) {
		  rootView = inflater.inflate(R.layout.fragment_contact_detail,
					container, false);
			Intent intent = this.getActivity().getIntent();
			String idContact = intent.getStringExtra("id");
			id = Long.valueOf(idContact);
			db = new DatabaseHandler(this.getActivity().getApplicationContext());
			Uri dataUri = ContactsContract.Data.CONTENT_URI;
			Cursor dataCursor = this.getActivity().getContentResolver().query(dataUri, null, 
					ContactsContract.Data.CONTACT_ID + "=" + id, 
					null, null);
			laoadUser(dataCursor,id);
			 
			return rootView;
		}
		



		

	     protected void laoadUser(Cursor dataCursor,long id) {
			
			List<Entry<String, Integer>> phones = new ArrayList<Entry<String, Integer>>();
			List<Entry<String, Integer>> emails = new  ArrayList<Entry<String, Integer>>();
			String displayName="";
			String nickName="";

			String photoPath=null;
			byte[] photoByte=null;

			String companyName="";
			String title="";
			String status=getString(R.string.invite).toUpperCase( Locale.getDefault());
			
			
			
			if(dataCursor.moveToFirst()){
				// Getting Display Name
				displayName = dataCursor.getString(dataCursor.getColumnIndex(ContactsContract.Data.DISPLAY_NAME ));
				do{
										
					// Getting NickName
					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Nickname.CONTENT_ITEM_TYPE))
						nickName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
					
					// Getting Phone numbers
					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)){
						Map<String , Integer> map = new HashMap<String, Integer>();
						map.put(dataCursor.getString(dataCursor.getColumnIndex("data1")), 1);
						phones.add(map.entrySet().iterator().next());
					}
					
					// Getting EMails
					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE ) ) {									
						Map<String , Integer> map = new HashMap<String, Integer>();
						map.put(dataCursor.getString(dataCursor.getColumnIndex("data1")), 1);
						emails.add(map.entrySet().iterator().next());
					}
					
					// Getting Organization details
					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)){
						companyName = dataCursor.getString(dataCursor.getColumnIndex("data1"));
						title = dataCursor.getString(dataCursor.getColumnIndex("data4"));
					}
						
					// Getting Photo	
					if(dataCursor.getString(dataCursor.getColumnIndex("mimetype")).equals(ContactsContract.CommonDataKinds.Photo.CONTENT_ITEM_TYPE)){								
						photoByte = dataCursor.getBlob(dataCursor.getColumnIndex("data15"));
						
						if(photoByte != null) {							
							Bitmap bitmap = BitmapFactory.decodeByteArray(photoByte, 0, photoByte.length);
							
							// Getting Caching directory 
		                    File cacheDirectory = this.getActivity().getBaseContext().getCacheDir();

		                    // Temporary file to store the contact image 
		                    File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+id+".png");

		                    // The FileOutputStream to the temporary file
		                    try {
								FileOutputStream fOutStream = new FileOutputStream(tmpFile);
								
								// Writing the bitmap to the temporary file as png file
			                    bitmap.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

			                    // Flush the FileOutputStream
			                    fOutStream.flush();

			                    //Close the FileOutputStream
			                    fOutStream.close();

							} catch (Exception e) {
								e.printStackTrace();
							}

		                    photoPath = tmpFile.getPath();
						}
						
					}
					
				}while(dataCursor.moveToNext());					
				
				ImageView photoImage = (ImageView)rootView.findViewById(R.id.profil_photo);
				if(photoPath!=null)
				{
					photoImage.setImageURI( Uri.parse(photoPath));
				}else{
					photoImage.setImageResource(R.drawable.ic_default_person);
				}
				
				getActivity().getActionBar()
		        .setTitle(displayName);
				
				buildList(phones, R.id.ls_phone,true);
				buildList(emails, R.id.ls_email,false);
				String details = "";
				
				// Concatenating various information to single string
				
				Contact contact = db.getContactContactId(id);
				
				if(contact==null)
				{
					 status=getString(R.string.join_out);
				
				}else if(contact.getServerid()<=0){
				
				    status=getString(R.string.join_out);
				}
				else{
				
					 status=getString(R.string.join_out);
				}

				// Adding id, display name, path to photo and other details to cursor
				
				
			}
			}
		
	  public void buildList(List<Entry<String, Integer>> list, int lst, boolean phone)
	  {
		    String[] from = { "phone", "purpose" };
		    int[] to = { android.R.id.text1, android.R.id.icon1 };
		    MyPerformanceArrayAdapter adapter = new MyPerformanceArrayAdapter(this.getActivity(),list);
		    adapter.setPhone(phone);
		    ListView lstPhone = (ListView) rootView.findViewById(lst);
		    lstPhone.setAdapter(adapter);
	  }
	  
	  public class MyPerformanceArrayAdapter extends ArrayAdapter<Map.Entry<String, Integer>> {
		  private final Activity context;
		  private final List<Entry<String, Integer>> datas;
		 boolean  phone;
		 
		   public boolean isPhone() {
			return phone;
		}

		public void setPhone(boolean phone) {
			this.phone = phone;
		}

		class ViewHolder {
		    public TextView text;
		    public ImageView image;
		  }

		  public MyPerformanceArrayAdapter(Activity context, List<Map.Entry<String, Integer>> datas) {
		    super(context, R.layout.emailphone_list, datas);
		    this.context = context;
		    this.datas = datas;
		  }

		  @Override
		  public View getView(int position, View convertView, ViewGroup parent) {
		    View rowView = convertView;
		    // reuse views
		    if (rowView == null) {
		      LayoutInflater inflater = context.getLayoutInflater();
		      rowView = inflater.inflate(R.layout.emailphone_list, null);
		      // configure view holder
		      ViewHolder viewHolder = new ViewHolder();
		      viewHolder.text = (TextView) rowView.findViewById(R.id.ep_emailphone);
		      viewHolder.image = (ImageView) rowView.findViewById(R.id.ep_icon);
		      rowView.setTag(viewHolder);
		    }

		    // fill data
		    ViewHolder holder = (ViewHolder) rowView.getTag();
		    Entry<String, Integer>  occurences = datas.get(position);
		    holder.text.setText(occurences.getKey());
		    if (occurences.getValue()>0) {
		    	if(phone)
		    	{
		    		 holder.image.setImageResource(R.drawable.ic_call);
		    	}
		    	else{
		    		 holder.image.setImageResource(R.drawable.ic_mail2);
		    	}
		     
		    } else {
		      holder.image.setImageResource(R.drawable.ic_launcher);
		    }

		    return rowView;
		  }
		}

	}

	
}
